package com.its.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.its.domain.BaseResult;
import com.its.member.pojo.Member;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * 会员登录成功处理器
 */
public class MyMemberLoginSuccessHandle implements AuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        // ✅ 将用户认证信息放入 Spring Security 的上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // ✅ 将上下文信息写入 Session 中（非常关键！）
        request.getSession().setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext()
        );


        // 清空密码字段，避免泄露
        Member member = (Member) authentication.getPrincipal();
        member.setMemberPassword(null);

        // ✅ 关键补充：写入 session 供后续接口使用
        request.getSession().setAttribute("memberAccount", member.getMemberAccount());

        // 构建返回结果
        BaseResult<Member> result = new BaseResult<>(200, "登录成功", member);
        response.setContentType("application/json;charset=utf-8");
        response.getOutputStream().write(objectMapper.writeValueAsBytes(result));
    }
}
